package com.ay.weixin.fdc.admin.customer.event;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;

import org.lizar.config.Config;
import org.lizar.controller.Event;
import org.lizar.controller.loader.EventLoader;
import org.lizar.ioc.Container;
import org.lizar.util.FileTool;
import org.lizar.util.StringHelper;
import org.lizar.util.pager.PageData;

import com.ay.weixin.config.ProjectConfig;
import com.ay.weixin.config.group.exception.ProjectNotExists;
import com.ay.weixin.fdc.admin.customer.db.IbatisCustomerDao;
import com.ay.weixin.fdc.admin.customer.db.IbatisWeiXinProjectDao;
import com.ay.weixin.fdc.admin.customer.domain.WeiXinProject;
import com.ay.weixin.fdc.admin.customer.domain.WeiXinProject.WeiXinProjectStatus;
import com.ay.weixin.fdc.admin.superadmin.domain.SuperAdmin;

public class ProjectManage extends Event {
	
	private static IbatisWeiXinProjectDao	projectDao;
	
	private static IbatisCustomerDao		customerDao;
	
	@Override
	public void init_property() throws Exception {
		projectDao = Container.get(IbatisWeiXinProjectDao.class);
		customerDao=Container.get(IbatisCustomerDao.class);
	}
	
	@Override
	public String default_handling_path() {
		return "/superadmin/wxproject/*";
	}
	
	@Override
	public void handle(EventLoader el) throws ServletException, IOException, SQLException {
		SuperAdmin adm = (SuperAdmin) el.getSessionAttr("adm");
		if (adm == null) {
			el.response(Config.xpathgetStr("server_info.root") + "/superadmin/login/");
		} else {
			if (StringHelper.equals(el.queryPath(2), "")) {
				index(el);
			} else if (StringHelper.equals(el.queryPath(2), "add_view")) {
				add_view(el);
			} else if (StringHelper.equals(el.queryPath(2), "add_submit")) {
				add_submit(el);
			} else if (StringHelper.equals(el.queryPath(2), "detail")) {
				detail(el);
			} else if (StringHelper.equals(el.queryPath(2), "update")) {
				update(el);
			}else if (StringHelper.equals(el.queryPath(2), "to_test")) {
				to_test(el);
			}else if (StringHelper.equals(el.queryPath(2), "to_start")) {
				to_start(el);
			}else if (StringHelper.equals(el.queryPath(2), "to_stop")) {
				to_stop(el);
			}else if (StringHelper.equals(el.queryPath(2), "delete")) {
				delete(el);
			}else if (StringHelper.equals(el.queryPath(2), "customer")) {
				customer(el);
			}
		}
	}
	
	private void customer(EventLoader el) throws IOException{
		
	}
	
	
	private void delete(EventLoader el) throws IOException, ServletException{
		long project_id=el.getLong("project_id");
		try {
			projectDao.delete(project_id);
			ProjectConfig.delete(project_id);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", "数据库异常:"+e.getLocalizedMessage());
			index(el);
			return;
		}
		File f=new File(el.getRealPath("/WEB-INF/template/app/"+project_id));
		System.out.println("开始删除页面模板:"+f.getPath());
	    FileTool.deleteFiles(f);
		f=new File(el.getRealPath("/static/app/"+project_id));
		System.out.println("开始删除静态资源:"+f.getPath());
		FileTool.deleteFiles(f);
		
		el.setAttr("msg","删除成功");
		index(el);
	}
	
	private void to_stop(EventLoader el) throws IOException, ServletException{
		long project_id=el.getLong("project_id");
		WeiXinProject project=null;
		try {
			project=projectDao.getById(project_id);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", "数据库异常:"+e.getMessage());
			index(el);
			return;
		}
		if(StringHelper.equals(project.getStatus(), WeiXinProjectStatus.STOP.name())){
			index(el);
			return;
		}
		project.setStatus(WeiXinProjectStatus.STOP.name());
		try {
			projectDao.update(project);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", "数据库异常:"+e.getLocalizedMessage());
		}
		try {
			ProjectConfig.remove(project_id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		el.setAttr("msg","更新成功");
		index(el);
	}
	
	private void to_start(EventLoader el) throws IOException, ServletException{
		long project_id=el.getLong("project_id");
		WeiXinProject project=null;
		try {
			project=projectDao.getById(project_id);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", "数据库异常:"+e.getMessage());
			index(el);
			return;
		}
		if(StringHelper.equals(project.getStatus(), WeiXinProjectStatus.START.name())){
			index(el);
			return;
		}
		project.setStatus(WeiXinProjectStatus.START.name());
		try {
			projectDao.update(project);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", "数据库异常:"+e.getLocalizedMessage());
			index(el);
			return;
		}
		
		el.setAttr("msg","更新成功");
		index(el);
	}
	
	private void to_test(EventLoader el) throws IOException, ServletException{
		long project_id=el.getLong("project_id");
		WeiXinProject project=null;
		try {
			project=projectDao.getById(project_id);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", "数据库异常:"+e.getMessage());
			index(el);
			return;
		}
		if(StringHelper.equals(project.getStatus(), WeiXinProjectStatus.TEST.name())){
			index(el);
			return;
		}
		project.setStatus(WeiXinProjectStatus.TEST.name());
		try {
			projectDao.update(project);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", "数据库异常:"+e.getLocalizedMessage());
		}
		el.setAttr("msg","更新成功");
		index(el);
	}
	
	private void add_view(EventLoader el) throws IOException, ServletException {
		el.setAttrs(el.getParams());
		el.setAttr("status_list", WeiXinProjectStatus.values());
		el.template("/WEB-INF/template/superadmin/wxproject/add.vm");
	}
	
	private void add_submit(EventLoader el) throws IOException, ServletException, SQLException {
		SuperAdmin 	adm = (SuperAdmin) el.getSessionAttr("adm");
		String		signDate=el.getStr("signDate");
		if(signDate!=null&&(signDate.length()!=8||!StringHelper.isInteger(signDate))){
			el.setAttr("msg", "签约时间不正确:"+signDate);
			add_view(el);
			return;
		}
		String 		name=el.getStr("name");
		try {
			if(projectDao.name_exists(name)){
				el.setAttr("msg", "项目名称已经存在:"+name);
				add_view(el);
				return;
			}
		} catch (SQLException e2) {
			e2.printStackTrace();
			el.setAttr("msg", "数据库异常:"+e2.getLocalizedMessage());
			index(el);
			return;
		}
		
		String 		company=el.getStr("company");
		String 		description=el.getStr("description");
		int			price=el.getInt("price");
		int 		paied=el.getInt("paied");
		int   		yearFee=el.getInt("yearFee");
		String 		status=WeiXinProjectStatus.INIT.name();
		String 		copyRight=el.getStr("copyRight");
		String		appId=el.getStr("appId");
		String 		appSecret=el.getStr("appSecret");
		String 		token=el.getStr("token");
		boolean		weixinOnly=el.getBool("weixinOnly");
		
		WeiXinProject project=new WeiXinProject();
		project.setAddTime(new Date());
		project.setUpdateTime(new Date());
		project.setCompany(company);
		project.setDescription(description);
		project.setName(name);
		project.setOperatorID(adm.getId());
		project.setPaied(paied);
		project.setPrice(price);
		try {
			project.setSignDate(new SimpleDateFormat("yyyyMMdd").parse(signDate));
		} catch (ParseException e1) {
			e1.printStackTrace();
			el.setAttr("msg", "签约时间不正确:"+signDate);
			add_view(el);
			return;
		}
		project.setStatus(status);
		project.setYearFee(yearFee);
		try {
			projectDao.insert(project);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", "数据库异常:"+e.getLocalizedMessage());
			index(el);
			return;
		}
		try {
			project=projectDao.get(name);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", "数据库异常:"+e.getLocalizedMessage());
			index(el);
			return;
		}
		if(project==null){
			el.setAttr("msg", "添加成功，但创建文件夹失败，查询异常");
			index(el);
			return;
		}
		FileTool.copyFolder(el.getRealPath("/WEB-INF/template/app/default"), el.getRealPath("/WEB-INF/template/app/"+project.getId()));
		FileTool.copyFolder(el.getRealPath("/static/app/default"), el.getRealPath("/static/app/"+project.getId()));
		try {
			ProjectConfig.createNewOrRefresh(project.getId());
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAppAttr("msg", e.getLocalizedMessage());
			index(el);
			return;
		} catch (ProjectNotExists e) {
			e.printStackTrace();
			el.setAppAttr("msg", e.getLocalizedMessage());
			index(el);
			return;
		}
		ProjectConfig.update(project.getId(),"sys.AppId", appId);
		ProjectConfig.update(project.getId(),"sys.AppSecret", appSecret);
		ProjectConfig.update(project.getId(),"sys.weixin_only", Boolean.toString(weixinOnly));
		ProjectConfig.update(project.getId(),"sys.token", token);
		ProjectConfig.update(project.getId(),"sys.copy_right", copyRight);
		
		index(el);
	}
	
	private void detail(EventLoader el) throws IOException, ServletException {
		int project_id=el.getInt("project_id");
		WeiXinProject project=null;
		try {
			project=projectDao.getById(project_id);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", "数据库异常:"+e.getMessage());
			index(el);
			return;
		}
		if(project==null){
			el.setAttr("msg", "不存在该项目:"+project_id);
			index(el);
			return;
		}
		el.setAttr("project",project);
		ProjectConfig.loadSysConfig(el,project_id);
		el.template("/WEB-INF/template/superadmin/wxproject/detail.vm");
	}
	
	private void update(EventLoader el) throws IOException, ServletException, SQLException {
		String		signDate=el.getStr("signDate");
		if(signDate!=null&&(signDate.length()!=8||!StringHelper.isInteger(signDate))){
			el.setAttr("msg", "签约时间不正确:"+signDate);
			detail(el);
			return;
		}
		int project_id=el.getInt("project_id");
		
		WeiXinProject project=null;
		try {
			project=projectDao.getById(project_id);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", "数据库异常:"+e.getMessage());
			detail(el);
			return;
		}
		if(project==null){
			el.setAttr("msg", "不存在该项目:"+project_id);
			detail(el);
			return;
		}
		
		String 		name=el.getStr("name");
		String 		company=el.getStr("company");
		String 		description=el.getStr("description");
		int			price=el.getInt("price");
		int 		paied=el.getInt("paied");
		int   		yearFee=el.getInt("yearFee");
		String 		copyRight=el.getStr("copyRight");
		String		appId=el.getStr("appId");
		String 		appSecret=el.getStr("appSecret");
		String 		token=el.getStr("token");
		boolean		weixinOnly=el.getBool("weixinOnly");
		
		project.setUpdateTime(new Date());
		project.setCompany(company);
		project.setDescription(description);
		project.setName(name);
		project.setPaied(paied);
		project.setPrice(price);
		try {
			project.setSignDate(new SimpleDateFormat("yyyyMMdd").parse(signDate));
		} catch (ParseException e1) {
			e1.printStackTrace();
			el.setAttr("msg", "签约时间不正确:"+signDate);
			add_view(el);
			return;
		}
		project.setYearFee(yearFee);
		try {
			projectDao.update(project);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", "数据库异常:"+e.getLocalizedMessage());
		}
		ProjectConfig.update(project.getId(),"sys.AppId", appId);
		ProjectConfig.update(project.getId(),"sys.AppSecret", appSecret);
		ProjectConfig.update(project.getId(),"sys.weixin_only", Boolean.toString(weixinOnly));
		ProjectConfig.update(project.getId(),"sys.token", token);
		ProjectConfig.update(project.getId(),"sys.copy_right", copyRight);
		
		el.setAttr("msg","更新成功");
		detail(el);
	}
	
	private void index(EventLoader el) throws IOException, ServletException {
		String status = el.getStr("status", WeiXinProjectStatus.INIT.name());
		String keywords = el.param("keywords", "", "utf-8");
		int page = el.getInt("page", 1);
		int size = 20;
		int total = 0;
		try {
			if (StringHelper.isNull(keywords)) {
				total = projectDao.countByStatus(status);
			} else {
				total = projectDao.countSearchByStatus(status, keywords);
			}
		} catch (Exception e) {
			e.printStackTrace();
			el.setAttr("msg", "数据库异常:"+e.getLocalizedMessage());
		}
		PageData<WeiXinProject> page_data = new PageData<WeiXinProject>(page, total, size, null);
		
		int start = page_data.getStart();
		
		List<WeiXinProject> list = null;
		
		try {
			if (StringHelper.isNull(keywords)) {
				list = projectDao.getByStatus(status, start, size);
			} else {
				list = projectDao.searchByStatus(status, keywords, start, size);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", "数据库异常:" + e.getLocalizedMessage());
		}
		page_data.setData(list);
		el.setAttr("page_data", page_data);
		el.setAttr("keywords", keywords);
		el.setAttr("keywords_encode", URLEncoder.encode(keywords, "utf-8"));
		el.setAttr("status", status);
		el.setAttr("status_list", WeiXinProjectStatus.values());
		el.setAttr("list", list);
		el.template("/WEB-INF/template/superadmin/wxproject/index.vm");
	}
	
}
